package com.example.toy.core.record.key.generator;

import lombok.SneakyThrows;
import org.apache.avro.Schema;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.List;

/**
 * HashKeyGenerator
 *
 * @author shenbing
 * @date 2021/12/17
 */
public class Md5HashKeyGenerator implements KeyGenerator {

  @SneakyThrows
  @Override
  public String generate(Schema schema, Object... params) {
    if (params == null || params.length == 0) {
      throw new IllegalArgumentException("HashKeyGenerator params can not be null or empty.");
    }
    MessageDigest m = MessageDigest.getInstance("MD5");
    for (Object param : params) {
      byte[] bytes = String.valueOf(param).getBytes(StandardCharsets.UTF_8);
      m.update(bytes, 0, bytes.length);
    }

    return Hex.encodeHexString(m.digest());
  }

  @Override
  public List<Object> fromKey(Schema schema, String key) {
    throw new UnsupportedOperationException("Unsupported from key to objects");
  }
}
